const Koa = require('koa');
const app = new Koa();
const fs = require('fs');

//静态文件中间件
const serve = require('koa-static');
app.use(serve(__dirname+'/static'));
app.use(serve('dist'));

//处理跨域中间件
var cors = require('koa2-cors');
app.use(cors());

//解析请求体中间件
const koaBody = require('koa-body');
app.use(koaBody());

const port = 9000;

//模拟延迟
function dydata(data) {
  return new Promise(function(resolve, reject) {
    setTimeout(function(){
      resolve(data)
    },249);

  });
}

//加入中间件,仅仅做了简单的路由
app.use(async ctx => {

  //获取商品列表
  if(ctx.path == '/getGoodsList'){
    ctx.body = { code:0, data: await dydata(require('./server.db.json').goods)};
  //获取用户信息
  }if(ctx.path == '/getGoodsDetails'){
    let query = ctx.request.query;
    if(query.id == undefined){
      ctx.body = '缺少请求参数!'
    }else{
      ctx.body = { code:0, data: await dydata(require('./server.db.json').goodsDetail[query.id])};
    }

  //获取用户信息
  }else if(ctx.path == '/getUserInfo'){
    ctx.body = { code:0, data: await dydata(require('./server.db.json').user)};

  //修改用户信息
  }else if(ctx.path == '/modifyUserInfo'){
    let body = ctx.request.body;
    if(body.name == undefined || body.sex == undefined || body.age == undefined|| body.photo == undefined){
      ctx.body =  { code:1, data: await dydata('缺少请求参数')};
    }else{
      let dbSource = require('./server.db.json');
      dbSource.user = body;
      //保存用户信息
      fs.writeFileSync(__dirname+'/server.db.json', JSON.stringify(dbSource));
      ctx.body = { code:0, data: await dydata('ok')};
    }
  }else if(ctx.path == '/getActivitys'){
    ctx.body = { code:0, data: await dydata(require('./server.db.json').activitys)};
  }

});

//运行node服务
app.listen(port);
console.log(`server is running : http://127.0.0.1:${port}`)
